#include "cgzCLua.h"
#include "cgzCThreadPool.h"
#include "cgzCSpdLog.h"

static int spdlog_new(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    int tref = luaL_ref(L, LUA_REGISTRYINDEX);
    void *node = malloc(sizeof(cgzCSpdLog));
    auto cobj = new (node) cgzCSpdLog(that->m_pool, name);
    cobj->m_tref = tref;
    lua_pushlightuserdata(L, cobj);
    return 1;
}

static int spdlog_set(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    auto cobj = (cgzCSpdLog *)lua_touserdata(L, 1);
    const char *fname = lua_tostring(L, 2);
    const bool console = lua_toboolean(L, 3);
    const uint8_t id = cobj->Customize(fname, console);
    lua_pushinteger(L, id);
    return 1;
}

static int spdlog_run(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    auto cobj = (cgzCSpdLog *)lua_touserdata(L, 2);
    that->m_pool->addTask(name, cobj);
    uint8_t logtid = cobj->getId();
    uint8_t logfid = lua_tointeger(L, 3);
    uint8_t loglvl = lua_tointeger(L, 4);
    that->m_pool->setLog(logtid,logfid,loglvl);
    return 0;
}

static int spdlog_log(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    const uint8_t fid = lua_tointeger(L, 2);
    const uint8_t flg = lua_tointeger(L, 3);
    const int len = lua_tointeger(L, 4);
    std::string msg;
    for (int i = 1; i <= len; i++)
    {
        lua_pushinteger(L, i); // 将索引推入栈中
        lua_gettable(L, 5);
        const char *value = lua_tostring(L, -1);
        msg.append(value);
        lua_pop(L, 1); // 弹出值
    }

    auto node = malloc(sizeof(cgzCSpdItem));
    auto item = new (node) cgzCSpdItem(fid, flg, msg);
    that->regTask(name, item);
    return 0;
}

int cgzCLua::luaopen_Spdlog(lua_State *L)
{
    static const luaL_Reg otherlib[] = {
        {"new", spdlog_new},
        {"set", spdlog_set},
        {"run", spdlog_run},
        {"log", spdlog_log},
        {NULL, NULL}};

    luaL_newlib(L, otherlib);
    return 1;
}